<template>
  <flexbox
    v-loading="loading"
    align="stretch"
    class="log-add"
    :class="{'is-edit': isEdit}">
    <xr-avatar
      :name="userInfo.realname"
      :size="32"
      :src="userInfo.img"
      class="user-img" />
    <div v-if="isUnfold" class="log-content">
      <div class="mix-content">
        <i
          v-if="helpObj"
          class="wk wk-icon-fill-help wk-help-tips"
          :data-type="helpObj.type"
          :data-id="helpObj.id" />
        <el-form
          ref="logForm"
          :model="fieldForm"
          :rules="fieldRules"
          :validate-on-rule-change="false"
          class="wk-form"
          label-position="top">
          <wk-form-items
            v-for="(children, cIndex) in fieldList"
            :key="cIndex"
            :field-from="fieldForm"
            :field-list="children"
            :ignore-fields="ignoreFields"
            @change="formChange"
          >
            <template slot-scope="{ data, index }">
              <div v-if="data.field == 'content'">
                <textarea-at
                  ref="at"
                  :detail-content="detailContent"
                  :common-words="fieldForm.content" />
                <!-- <wk-field
                  :item="data"
                  :index="index"
                  :field-from="fieldForm"
                  @change="formChange"
                /> -->
                <div class="content-bar">
                  <common-words
                    :props="commonWordsProps"
                    :set-props="commonWordsSetProps"
                    :help-obj="commonHelpObj"
                    @select="commonWordsSelect" />
                </div>
              </div>
            </template>
          </wk-form-items>
        </el-form>

        <div class="other-content">
          <add-image-list
            v-if="imgFiles.length > 0"
            :data="imgFiles"
            @delete="deleteImage"
            @delete-all="deleteAllFile(2)"
            @upload="uploadFile" />
          <!-- 附件 -->
          <div v-if="files.length > 0" class="content-title">
            {{ $t('crm.components.65df91411a3121612ee441f880bacd12',{1: files.length }) }}
          </div>
          <add-file-list
            v-if="files.length > 0"
            :data="files"
            @delete="deleteFile"
            @delete-all="deleteAllFile(1)" />
          <div v-if="allDataLen" class="content-title">
            {{ $t('crm.components.b48593626d4f94ea1082e42cf8e0ca39',{1: allDataLen }) }}
          </div>
          <related-business
            ref="relatedBusiness"
            :margin-left="'0'"
            :all-data="showRelateData"
            :show-add-btn="false"
            :show-foot="true"
            @unbind="deleteRelate" />
          <div v-show="!loading" class="add-control">
            <div class="control-item" @click="barClick('img')">
              <el-tooltip
                effect="dark"
                :content="$t('crm.components.8f07195b139afc5d604f525655964011')"
                placement="top">
                <span class="icon wk wk-picture" />
              </el-tooltip>
            </div>
            <div class="control-item" @click="barClick('file')">
              <el-tooltip
                effect="dark"
                :content="$t('crm.components.388420dcda82dea18b61c409bea85ae2')"
                placement="top">
                <span class="icon wk wk-file" />
              </el-tooltip>
            </div>
            <crm-relative
              v-if="showRelatePopover"
              ref="crmrelative"
              :visible.sync="showRelatePopover"
              :radio="false"
              :show-types="[
                'customer',
                'contacts',
                'business',
                'contract',
                'receivables',
                'product'
              ]"
              :selected-data="relateData"
              :props="crmRelativeProps"
              @close="showRelatePopover= false"
              @changeCheckout="relateDataChange" />
            <div
              v-if="config.showRelativeAdd"
              class="control-item"
              @click="barClick('relate')">
              <el-tooltip
                effect="dark"
                :content="$t('crm.components.ecef3f671920c61d1f15ad2fa6cae9a6')"
                placement="top">
                <span class="icon wk wk-associated" />
              </el-tooltip>
            </div>
          </div>
        </div>

        <div v-show="!loading && !isEdit" class="send-bar">
          <el-button v-debounce="sendClick" type="primary">
            {{ $t('crm.components.15a6cb287506a3c60cdc4608ad6c25fe') }}
          </el-button>
          <el-button v-debounce="close">
            {{ $t('crm.components.e26b0f9e6858af1c7cbaf2d7ac48425e') }}
          </el-button>
        </div>

        <!-- 附件 -->
        <input
          ref="fileInput"
          accept="*.*"
          type="file"
          class="file-input"
          multiple
          @change="uploadFile">
        <input
          ref="imgInput"
          accept="image/*"
          type="file"
          class="file-input"
          multiple
          @change="uploadFile">
      </div>
    </div>
    <div
      v-else
      style="flex: 1;"
      class="mix-content wk-no-border-backgroud-form unfold">
      <div class="i-cont unfold" @click="inputFocus">
        <!-- <i
            class="wk wk-write" /> -->
        <span>{{ $t('crm.components.ca165c3981b00dc9d3b6f474d1658ff8') }}</span>
      </div>
    </div>

  </flexbox>
</template>

<script>
import { crmFileDeleteAPI, crmFileRemoveByBatchIdAPI } from '@/api/common'
import {
  sysConfigQueryPhraseAPI,
  sysConfigSetPhraseAPI,
  crmActivityFieldAPI,
  crmActivityFieldEditAPI
} from '@/api/crm/common'

import AddImageList from '@/components/QuickAdd/AddImageList'
import AddFileList from '@/components/QuickAdd/AddFileList'
import CommonWords from '@/components/CommonWords'
import WkFormItems from '@/components/NewCom/WkForm/WkFormItems'
import RelatedBusiness from '@/components/RelatedBusiness'
// import WkField from '@/components/NewCom/WkForm/WkField'
import TextareaAt from '@/components/At'

import {
  fileSize,
  getFileTypeIcon,
  guid,
  objDeepCopy,
  getFileIconWithFileName
} from '@/utils/index'
import EmitterMixin from '@/mixins/Emitter'
import { mapGetters } from 'vuex'
import CustomFieldsMixin from '@/mixins/CustomFields'
import merge from '@/utils/merge'

const DefaultLogAdd = {
  showRelativeAdd: true // 默认展示相关业务添加
}

export default {
  /** 跟进记录 下的 添加 有添加框的都需要*/
  name: 'LogAdd',
  components: {
    CrmRelative: () => import('@/components/CreateCom/CrmRelative'),
    AddImageList,
    AddFileList,
    CommonWords,
    WkFormItems,
    RelatedBusiness,
    // WkField,
    TextareaAt
  },
  mixins: [EmitterMixin, CustomFieldsMixin],
  props: {
    // 日志详情用于编辑
    logData: null,
    // 模块ID
    id: [String, Number],
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: ''
    },
    props: Object,
    // 关联业务筛选
    crmRelativeProps: Object
  },
  data() {
    return {
      loading: false,
      isUnfold: false, // 默认闭合
      relateData: {},
      /** 图片信息 */
      imgFiles: [],
      /** 图片信息 */
      files: [],
      /** 关联商机信息 */
      showRelativeType: '',
      showRelatePopover: false,
      business: [],
      timeOptions: [
        { label: this.$t('crm.components.5d0bb66ad758f4c668152b2fcc33b6aa'), value: 1 },
        { label: this.$t('crm.components.d3d3fbfc2348c111d51df3baebad8970'), value: 2 },
        { label: this.$t('crm.components.e8df75b0b0096c8a22bf0912247ffd4b'), value: 3 },
        { label: this.$t('crm.components.659a875d344994b1b29be2c90db9e340'), value: 4 },
        { label: this.$t('crm.components.e032fcd1dc8cfdcc228bbe56ddd723a8'), value: 5 },
        { label: this.$t('crm.components.2e5475b6abb392f0a321df1b97472ef0'), value: 6 },
        { label: this.$t('crm.components.ddb47e287fefd9da64cd14c90a75da91'), value: 7 },
        { label: this.$t('crm.components.61bacd205cbf76917d186423fb98d2d2'), value: 8 },
        { label: this.$t('crm.components.1db5d58bda17382438c77233fdae7d1b'), value: 9 }
      ],
      /** 展示关联弹窗 */
      batchId: guid(), // 批次ID

      fieldList: [],
      fieldForm: {},
      fieldRules: {},
      resetFieldData: {
        fieldForm: {},
        fieldRules: {}
      }, // 用于重置页面的信息

      userVal: []
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'isWxUser'
    ]),

    ignoreFields() {
      // 企业微信关闭@功能
      return this.isWxUser ? [] : ['content']
    },

    // 合并 props
    config() {
      return merge({ ...DefaultLogAdd }, this.props || {})
    },

    // 是编辑
    isEdit() {
      return !!this.logData
    },

    // 帮助信息
    helpObj() {
      return {
        leads: {
          type: '7',
          id: '49'
        }, customer: {
          type: '8',
          id: '153'
        }, business: {
          type: '10',
          id: '154'
        }, contract: {
          type: '11',
          id: '63'
        }
      }[this.crmType] || null
    },
    // 常用语帮助
    commonHelpObj() {
      return {
        leads: {
          type: '7',
          id: '89'
        }, customer: {
          type: '8',
          id: '90'
        }, contacts: {
          type: '9',
          id: '91'
        }, business: {
          type: '10',
          id: '92'
        }, contract: {
          type: '11',
          id: '93'
        }
      }[this.crmType] || null
    },

    // 常用语配置
    commonWordsProps() {
      return {
        request: sysConfigQueryPhraseAPI // 添加请求和参数
      }
    },

    // 常用语设置配置
    commonWordsSetProps() {
      return {
        request: sysConfigSetPhraseAPI // 添加请求和参数
      }
    },
    allDataLen() {
      let res = 0
      if (!this.relateData) return res
      const keys = ['business', 'contacts', 'contract', 'customer', 'product']
      keys.forEach(key => {
        if (this.relateData[key]) {
          res += this.relateData[key].length
        }
      })
      return res
    },
    showRelateData() {
      const tempsData = {}
      Object.keys(this.relateData).forEach(key => {
        const list = this.relateData[key]
        if (list && list.length) {
          tempsData[key] = list
        }
      })
      return tempsData
    },

    detailContent() {
      return this.logData?.content || ''
    }
  },
  watch: {
    isUnfold() {
      if (this.isUnfold && this.fieldList.length === 0) {
        this.initEditInfo()
      }
    }

    // id: {
    //   handler() {
    //     this.businessAction = { type: 'condition', data: { moduleType: this.crmType, customerId: this.id }}
    //   },
    //   immediate: true
    // }
  },
  created() {
    this.isUnfold = this.isEdit
  },

  beforeDestroy() {},
  methods: {
    /**
     * 初始化编辑数据
     */
    initEditInfo() {
      if (this.logData) {
        const editFormData = objDeepCopy(this.logData)

        if (editFormData.batchId) {
          this.batchId = editFormData.batchId
        }

        // 编辑时引用 - 自动勾选
        var allData = {}
        allData.business = (editFormData.businessList || []).map(item => {
          if (item.id) {
            item.businessId = item.id
          }
          return item
        })
        allData.contacts = (editFormData.contactsList || []).map(item => {
          if (item.id) {
            item.contactsId = item.id
          }
          return item
        })
        allData.contract = (editFormData.contractList || []).map(item => {
          if (item.id) {
            item.contractId = item.id
          }
          return item
        })
        allData.customer = (editFormData.customerList || []).map(item => {
          if (item.id) {
            item.customerId = item.id
          }
          return item
        })
        allData.receivables = (editFormData.receivablesList || []).map(item => {
          if (item.id) {
            item.receivablesId = item.id
          }
          return item
        })
        allData.product = (editFormData.productList || []).map(item => {
          if (item.id) {
            item.productId = item.id
          }
          return item
        })
        this.relateData = allData

        // 图片 附件
        this.imgFiles = objDeepCopy(editFormData.img || [])
        // for (let index = 0; index < this.imgFiles.length; index++) {
        //   this.setImageList(this.imgFiles[index], index)
        // }
        this.files = objDeepCopy(editFormData.file || []).map(item => {
          item.icon = getFileIconWithFileName(item.name)
          return item
        })
      }
      this.getFieldData()
    },

    /**
     * @description: 获取初始化配置信息
     * @return {*}
     */
    getFieldData() {
      const request = this.isEdit ? crmActivityFieldEditAPI : crmActivityFieldAPI
      const params = this.isEdit ? this.id : null

      this.loading = true
      request(params).then(res => {
        const list = res.data || []
        const fieldList = []
        const fieldForm = {}

        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = this.getFormItemDefaultProperty(item)
            temp.show = true
            const canEdit = this.getItemIsCanEdit(item, this.isEdit ? 'update' : 'save')
            // 是否可编辑
            temp.disabled = !canEdit
            // 特殊字段允许多选
            this.getItemRadio(item, temp)

            // 获取默认值
            if (temp.show) {
              fieldForm[temp.field] = this.getItemValue(item, this.formData, this.isEdit ? 'update' : 'save')
            }
            fields.push(temp)
          })
          fieldList.push(fields)
        })
        this.fieldList = fieldList

        const result = this.getFormContentByOptionsChange(fieldList, fieldForm)
        this.fieldForm = result.fieldForm
        this.fieldRules = result.fieldRules

        // 重置页面用
        this.resetFieldData = objDeepCopy(result)

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
          field.remark === 'options_type' &&
          field.optionsData) {
        const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
        this.fieldForm = fieldForm
        this.fieldRules = fieldRules
      }

      const contentValue = !!(this.fieldForm.content && this.fieldForm.content.length > 0)

      if (!this.isEdit) {
        this.dispatch('SlideView', 'setEditClose', [contentValue])
      }
    },

    /**
     * 重置数据
     */
    resetInfo() {
      this.isUnfold = false
      // 输入法
      this.dispatch('SlideView', 'setEditClose', [false])
      // 图片信息
      this.imgFiles = []
      // 图片信息
      this.files = []
      // 展示关联弹窗
      this.showRelativeType = ''
      this.batchId = guid()
      // 重置表单
      const result = objDeepCopy(this.resetFieldData)
      this.fieldForm = result.fieldForm
      this.fieldRules = result.fieldRules
    },

    /**
     * 常用语选择
     */
    commonWordsSelect(data) {
      if (this.fieldForm.content) {
        this.$confirm(
          this.$t('crm.components.383575e131512356cf677521b7fc75ff'),
          this.$t('crm.components.5811dd17ec1bd54bd1d04b74dc76e5d0'), {
            confirmButtonText: this.$t('crm.components.226fa7a824256a0cf297f8f435845d90'),
            cancelButtonText: this.$t('crm.components.becf933fa11f7c5d8b526049dba6ceaa'),
            type: 'warning',
            customClass: 'is-particulars'
          })
          .then(() => {
            this.fieldForm.content = data
          })
          .catch(() => {})
      } else {
        this.fieldForm.content = data
      }
    },

    /**
     * @description: 底部栏事件
     * @param {*} type
     * @return {*}
     */
    barClick(type) {
      this.showRelativeType = type
      if (type == 'relate') {
        this.showRelatePopover = true
      } else if (type == 'file') {
        this.$refs.fileInput.click()
      } else if (type == 'img') {
        this.$refs.imgInput.click()
      }
    },

    /**
     * 关联业务选择
     */
    relateDataChange(val) {
      this.showRelatePopover = false
      this.relateData = val.data
    },

    /**
     * 删除相关
     */
    deleteRelate(type, data, index) {
      this.relateData[type].splice(index, 1)
    },

    /**
     * 图片选择出发
     */
    uploadFile(event) {
      var files = event.target.files
      if (files.length) {
        for (let index = 0; index < files.length; index++) {
          const file = files[index]
          if (
            file.type.indexOf('image') == -1 &&
            this.showRelativeType == 'img'
          ) {
            this.$message.error(this.$t('crm.components.4904da11b5cfd26dfce6c1fdb1944c25'))
            return
          }
        }

        var type = event.target.accept == 'image/*' ? 'img' : 'file'
        for (let index = 0; index < files.length; index++) {
          const file = files[index]
          this.uploadFileRequest(file, type)
        }
        event.target.value = ''
      }
    },

    /**
     * 文件上传
     */
    uploadFileRequest(file, type, result) {
      this.$wkUploadFile.upload({
        file: file,
        params: {
          type: type,
          batchId: this.batchId
        }
      }).then(({ res }) => {
        const data = res.data || {}
        data.size = fileSize(file.size)
        if (type == 'img') {
          this.imgFiles.push(data)
        } else {
          data['icon'] = getFileTypeIcon(file)
          this.files.push(data)
        }
        if (result) {
          result()
        }
      }).catch(() => {})
    },

    /**
     * 图片附件删除
     */
    deleteImage(item, index) {
      this.deleteImgOrFile('image', item, index)
    },

    deleteFile(item, index) {
      this.deleteImgOrFile('file', item, index)
    },

    deleteImgOrFile(type, item, index) {
      this.$confirm(
        this.$t('crm.components.d11d60c332996edb15ffeca2da1e7af7'),
        this.$t('crm.components.d91eaef621d159255e39ccddd1122147'),
        {
          confirmButtonText: this.$t('crm.components.9bcd9d719a9bba67166955d9ac782a1b'),
          cancelButtonText: this.$t('crm.components.e3ef3d7c70049c11f19ac707580e2679'),
          type: 'warning'
        }
      )
        .then(() => {
          crmFileDeleteAPI({
            id: item.fileId
          })
            .then(res => {
              if (type == 'image') {
                this.imgFiles.splice(index, 1)
              } else {
                this.files.splice(index, 1)
              }
              this.$message.success(this.$t('crm.components.18ba1e856ba9e4380d4449e99708f254'))
            })
            .catch(() => {})
        })
        .catch(() => {})
    },

    /**
     * 删除全部 type 1 是附件 2 是图片
     */
    deleteAllFile(type) {
      if (this.batchId) {
        this.$confirm(
          this.$t('crm.components.67cc0465be25d0e2f78c7f0736951536'),
          this.$t('crm.components.6a569a37070d97a24c14758d18929f4f'),
          {
            confirmButtonText: this.$t('crm.components.8a570b5d64a9cc9220937778b4f67503'),
            cancelButtonText: this.$t('crm.components.1cdc51fc28863b35a14dca4a8ad1cad0'),
            type: 'warning'
          }
        )
          .then(() => {
            crmFileRemoveByBatchIdAPI({
              batchId: this.batchId,
              type
            })
              .then(res => {
                if (type == 2) {
                  this.imgFiles = []
                } else {
                  this.files = []
                }
                this.$message.success(this.$t('crm.components.2fb6cc2549fc0ce0f798abead3956de8'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    },

    inputFocus() {
      this.isUnfold = true
      // this.$nextTick(() => {
      //   if (this.$refs.textarea) {
      //     this.$refs.textarea.focus()
      //   }
      //   this.$emit('focus')
      // })
    },

    /**
     * 发布
     */
    sendClick() {
      let atUserId = []
      if (!this.isWxUser) {
        const { atList, content, value = '' } = this.$refs.at[0].getAtData()

        this.fieldForm.content = value ? content : ''
        atUserId = atList
      }

      const logForm = this.$refs.logForm
      logForm.validate(valid => {
        if (valid) {
          if (this.fieldForm.content.length > 2000) {
            return this.$message.error('字数不能超过2000字')
          }

          const filedParams = this.getSubmiteParams([].concat.apply([], this.fieldList), this.fieldForm)
          const relateData = {}
          for (var key in this.relateData) {
            relateData[`${key}Ids`] = this.relateData[key].map(item => item[`${key}Id`])
          }

          const params = {
            ...filedParams.entity,
            field: filedParams.field,
            ...relateData,
            // files: this.files,
            // images: this.imgFiles,
            batchId: this.batchId,
            atUserId
          }

          if (this.isEdit) {
            params.id = this.id
          }

          this.$emit('send', params)
        } else {
          this.loading = false
          // 提示第一个error
          this.getFormErrorMessage(logForm)
          return false
        }
      })
    },

    /**
     * 关闭
     */
    close() {
      this.isUnfold = false
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.log-add {
  &.is-edit {
    .user-img,
    .wk-help-tips {
      display: none;
    }

    .mix-content {
      border: none;
    }
  }

  .log-content {
    flex: 1;
    width: 0;
  }
}

.mix-content {
  position: relative;
  padding: 8px #{$--interval-base * 2} #{$--interval-base * 3};
  border: 2px solid $--border-color-base;
  border-radius: $--border-radius-base;

  .wk-help-tips {
    position: absolute;
    right: 8px;
  }

  .interval-line {
    position: relative;

    &::after {
      position: absolute;
      top: 4px;
      bottom: 4px;
      left: -16px;
      width: 1px;
      content: " ";
      background-color: $--color-n30;
      border-radius: 1px;
    }
  }

  .i-cont {
    padding: $--interval-base 0;

    .wk-write {
      color: $--input-placeholder-color;
    }
  }
}

.content-title {
  margin-bottom: $--interval-base;
  font-weight: bold;
  color: $--color-text-secondary;
}

.other-content {
  padding: 0 16px;
  margin-top: 8px;
}

.add-control {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 8px;

  .control-item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    cursor: pointer;

    .icon {
      margin-right: 5px;
    }

    &:hover {
      color: $--color-primary;

      .add-user-btn {
        border-color: $--color-primary;
      }
    }
  }

  .control-relevance {
    .el-switch {
      margin: 0 8px;
    }
  }
}

.mix-content.unfold {
  padding: 0;
  color: $--input-placeholder-color;
  cursor: text;

  .i-cont {
    padding: 0 #{$--interval-base * 3};
    line-height: 40px;
  }
}

.file-input {
  display: none;
}

.send-bar {
  padding: 0 #{$--interval-base * 2};
  margin-top: #{$--interval-base * 2};
}

.user-img {
  flex-shrink: 0;
  margin-top: 5px;
  margin-right: $--interval-base;
}

.content-bar {
  line-height: 40px;
  text-align: right;
}
</style>
